import axios from 'axios'
import { Toast } from 'vant'

export const http = axios.create({
  timeout: 15000,
  baseURL: import.meta.env.VITE_API_BASE + '/dispose',
  headers: {
    'Content-Type': 'application/json'
  }
})

export default http

http.interceptors.request.use(
  async (config) => {
    // toggleLoading(config)
    return config
  },
  (error) => {
    console.error(error)
    // toggleLoading()
    if (error instanceof Error) {
      handleCommonError(error)
    }
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  (res) => {
    // toggleLoading(res.config)
    handleBusiError(res.data, res.config)
    return res.data
  },
  (error) => {
    console.error(error)
    // toggleLoading(error?.config)
    if (axios.isAxiosError(error)) {
      handleHttpError(error?.response)
    } else if (error instanceof Error) {
      handleCommonError(error)
    }
    return Promise.reject(error)
  }
)

/** 错误处理函数 分三个等级 */

function handleBusiError(data, config) {
  if (data?.ret !== 0) {
    const msg = data?.msg || 'Unknown API Error'
    showErrorToast(msg, config)
  }
}

function handleHttpError(res) {
  const unknownError = 'Unknown HTTP Error'
  if (!res) {
    return unknownError
  } else if (res.status) {
    const msg = `HTTP Error ${res.status}${
      res.data?.msg ? `: ${res.data.msg}` : ''
    }`
    showErrorToast(msg, res.config)
    return msg
  }
}

function handleCommonError(error) {
  if (axios.isAxiosError(error) && error.config) {
    showErrorToast(error.message, error.config)
  }
  return error.message
}

function toggleLoading(config) {
  if (!config || config.loading) {
    Toast.clear()
    config.loading = false
  } else if (config.showLoading && !config.loading) {
    Toast.loading({
      duration: 0,
      forbidClick: true
    })
    config.loading = true
  }
}

function showErrorToast(msg, config) {
  if (config?.showErrorToast) {
    Toast(msg)
  }
}
